package gb

import (
	"net/http"

	"gitee.com/tonyjia/gb28181/pkg/gbsip"
	"gitee.com/tonyjia/gb28181/pkg/model"
	"github.com/ghettovoice/gosip/sip"
	"github.com/jart/gosip/sdp"
	log "github.com/sirupsen/logrus"
)

/**
 * @Description
 * @Author lulili
 * @Date 2024/11/4 16:49
 */

func InviteHandler(req sip.Request, tx sip.ServerTransaction) {
	//先回复100
	log.Infof("接收到Invite消息%v", req)
	response100(tx, req)
	//然后解析这个请求 记录这个channel
	// 解析SDP内容
	sd, err := sdp.Parse(req.Body())
	if err != nil {
		log.Errorf("解析SDP失败：%v\n", err)
		return
	}
	var ssrc string
	for _, other := range sd.Other {
		if other[0] == "y" {
			ssrc = other[1]
		}
	}
	steamInfo := model.StreamInfo{
		ChannelId:     sd.Origin.User,
		Ip:            sd.Addr,
		MediaServerId: int(sd.Video.Port),
		Ssrc:          ssrc,
	}
	//获取通道id之后需要查询通道信息 才能构建发送invite请求
	newSdp, err := gbsip.SyncInvite(steamInfo)
	if err != nil {
		log.Error("同步sdp消息失败", err)
		return
	}
	//返回200 sdp消息 构建sdp
	mediaServer := model.MediaServer{
		IP:   newSdp.Ip,
		Port: newSdp.MediaServerId,
	}
	body := gbsip.CreateSdpInfo(newSdp.ChannelId, newSdp.Ssrc, mediaServer)
	tx.Respond(sip.NewResponseFromRequest("", req, http.StatusOK, http.StatusText(http.StatusOK), body))
}
